package http

import (
	"encoding/json"
	"fmt"
	"net/http"
	"oauth2/configs"
	"oauth2/initialize"
	"oauth2/libs"
	"oauth2/model"
	"oauth2/rpcservice"
	"strconv"
)
var GetMe = APIWrapper(GetUserInfo)


func APIWrapper(viewFunc func(w http.ResponseWriter, r *http.Request)) func(w http.ResponseWriter, r *http.Request) {
	wrapperFunc := func(w http.ResponseWriter, r *http.Request) {
		fmt.Println("执行前执行了")
		//验证token是否有效
		fmt.Println("r:",r)
		token, err := configs.Srv.ValidationBearerToken(r)
		fmt.Println("token:",token)
		if err != nil {
			//http.Error(w, err.Error(), http.StatusBadRequest)
			w.WriteHeader(200)
			w.Write(libs.Res(libs.ReturnJson(203, "Token已失效", err.Error())))
			return
		}
		viewFunc(w,r)
		return
	}
	return wrapperFunc
}

//获取用户信息
func GetUserInfo(w http.ResponseWriter, r *http.Request) {
	//获取url参数
	values := r.URL.Query()
	uidStr := values.Get("user_id")
	//缓存
	userinfo := initialize.RedisClient.Get("member:userinfo:"+uidStr)
	fmt.Println("redis userinfo:",userinfo)
	if userinfo.Val() != ""{
		var redisUser model.ProtoUserRes
		json.Unmarshal([]byte(userinfo.Val()), &redisUser.Result)
		msg, _ := json.Marshal(libs.ReturnJson(200, "", redisUser))
		w.Write(msg)
		return
	}
	uid, err := strconv.ParseInt(uidStr, 10, 64)
	result,err := rpcservice.MemberService.GetUserInfo(uid)

	msg, _ := json.Marshal(libs.ReturnJson(400,"","验证失败"))
	w.Header().Set("content-type","text/json")
	//返回结果是[]byte
	//fmt.Printf("res的数据类型为：%v\n", reflect.TypeOf(result))
	if err == nil {
		msg, _ = json.Marshal(libs.ReturnJson(200, "", result))
		w.Write(msg)
		//initialize.RedisClient.Set("oauth:userinfo:"+uidStr, msg,-1)
	}else{
		w.WriteHeader(400)
		w.Write(libs.Res(libs.ReturnJson(400, "", err.Error())))
	}
	return
}
